<?php

namespace app\controller;

use app\exception\UserNotFoundException;
use app\exception\UserPasswordErrorFoundException;
use app\exception\UserTokenExpiredException;
use app\model\User as UserModel;
use think\Request;
use think\response\Json;

class User
{
    /**
     * 用户登录
     * @param Request $request
     * @return Json 错误提示|用户信息
     */
    public function login(Request $request){

        // 学号，密码
        $studentNumber = $request->param('studentNumber');
        $password = $request->param('password');

        // 判断学号，密码合法性
        if (empty($studentNumber) || empty($password)) {
            return json([
                'code' => 400,
                'msg' => "学号或密码不能为空！"
            ]);
        }

        try {

            // 用户登录
            $result = UserModel::login($studentNumber, $password);

            // 登录成功
            return json([
                'code'=>200,
                'msg'=>"登录成功",
                'data'=>$result
            ]);

        }catch (UserNotFoundException | UserPasswordErrorFoundException $e){

            //用户不存在或密码错误
            return json([
                'code'=>$e->getCode(),
                'msg'=>$e->getMessage()
            ]);

        }catch (\Exception $e){

            // 系统异常
            return json([
                'code'=>500,
                'msg'=>'系统异常'
            ]);

        }

    }

    /**
     * 验证登录状态
     * @param Request $request
     * @return Json 登录状态信息
     */
    public function isLogin(Request $request){
        // token
        $token = $request->param('token');

        try {

            // 查询token是否有效
            $result = UserModel::isLogin($token);

            // token有效
            return json([
                'code'=>200,
                'msg'=>"登录状态正常",
                'data'=>$result
            ]);

        }catch (UserTokenExpiredException $e){

            // token过期
            return json([
                'code'=>$e->getCode(),
                'msg'=>$e->getMessage()
            ]);

        }catch (\Exception $e){

            // 系统异常
            return json([
                'code'=>500,
                'msg'=>'系统异常'
            ]);

        }

    }
}